<template>
  <div style="margin-top: 10px; margin: 10px; ">
    <!--搜索表单-->
    <el-form :inline="true" :model="disciple" class="demo-form-inline">
      <el-form-item label="姓名" >
        <el-input
            style="width: 140px; "
            v-model="disciple.name"
            placeholder="请输入员工姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="职位">
        <el-select v-model="disciple.job" placeholder="请选择" value-key="emp.job" style="width:100px">
          <el-option
              v-for="item in jobList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="归属部门">
        <el-select v-model="disciple.deptId" placeholder="请选择" style="width:100px">
          <el-option
              v-for="item in deptList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="入职时间">
        <el-date-picker
            v-model="entrydate"
            clearable
            value-format="yyyy-MM-dd"
            type="daterange"
            placeholder="选择日期"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 300px; "
        ></el-date-picker>
      </el-form-item>

      <el-form-item style="float: right">
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
    <!--添加数据对话框表单-->
    <el-dialog ref="form" title="编辑教员" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="disciple" label-width="80px" size="mini">
        <el-form-item label="用户名">
          <el-input v-model="disciple.username"></el-input>
        </el-form-item>
        <el-form-item label="员工姓名">
          <el-input v-model="disciple.name"></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="disciple.gender" placeholder="请选择" style="width:100%">
            <el-option
                v-for="item in genderList"
                :key="item.value"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8081/upload"
              :headers="{token}"
              name="image"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img  style="width: auto; height: 100px; border: none; cursor: pointer" v-if="disciple.image" :src="disciple.image" class="avatar" alt=""/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="职位">
          <el-select v-model="disciple.job" placeholder="请选择" value-key="emp.job" style="width:100%">
            <el-option
                v-for="item in jobList"
                :key="item.value"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="入职日期">
          <el-date-picker
              v-model="disciple.entrydate"
              clearable
              type="date"
              placeholder="选择日期"
              size="small"
              style="width:100%"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="归属部门">
          <el-select v-model="disciple.deptId" placeholder="请选择" style="width:100%">
            <!--
            <el-option label="学工部" value="1"></el-option>
            <el-option label="教研部" value="2"></el-option>
             -->
            <el-option
                v-for="item in deptList"
                :key="item.value"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="adds">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <br>


    <!--表格-->
    <template>
      <el-table
          highlight-current-row
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
      >

        <el-table-column type="index" width="80" label="序号" header-align="center" align="center"></el-table-column>

        <el-table-column prop="name" label="姓名" width="80" header-align="center" align="center"></el-table-column>
        <el-table-column prop="image" label="图像" width="120" header-align="center" align="center">
          <template slot-scope="{ row }">
            <el-image style="width: auto; height: 50px; border: none; cursor: pointer" :src="row.image"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="100" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="entrydate" label="入教日期" width="140" header-align="center"
                         align="center"></el-table-column>
        <el-table-column prop="job" label="职位" width="100" header-align="center" align="center">
          <template slot-scope="scope">
            {{ getJobListName(scope.row.job) }}
          </template>
        </el-table-column>
        <el-table-column prop="deptId" label="部门" width="80" header-align="center" align="center">
          <template slot-scope="scope">
            {{ getDepartmentName(scope.row.deptId) }}
          </template>
        </el-table-column>

        <el-table-column label="最后操作时间" header-align="center" align="center">
          <template slot-scope="scope">
            {{ scope.row.updateTime ? scope.row.updateTime.replace('T', ' ') : '' }}
          </template>
        </el-table-column>


        <el-table-column label="操作" width="300" header-align="center" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                plain
                @click="updateinfo(scope.row.id)"
            >编辑
            </el-button>

            <el-button
                size="mini"
                type="danger"
                plain
                @click="deletebyId(scope.row.id)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>


    <br>
    <!--分页工具条-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :background="background"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
    </el-pagination>

  </div>
</template>

<script>
import {deleteById, selectAll} from "@/api/emp";
import {update} from "@/api/emp";
import {add} from "@/api/emp";
import {selectById} from "@/api/emp";
import {getJoblist} from "@/api/emp";
import {findAll} from "@/api/dept";
import emp from "@/views/eui/emp.vue";
import {emppage} from "@/api/emp";
import index from "vuex";
import {getToken} from "@/utils/auth";
import Router from "@/router";
import axios from "axios";

export default {
  computed: {
    index() {
      return index
    }
  },
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 数据
      disciple: {
        createTime: "",
        deptId: "",
        entrydate: "",
        gender: "",
        id: "",
        image: "",
        job: "",
        name: "",
        password: "",
        updateTime: "",
        username: "",
      },
      emp: {
        createTime: "",
        deptId: "",
        entrydate: "",
        gender: "",
        id: "",
        image: "",
        job: "",
        name: "",
        password: "",
        updateTime: "",
        username: "",
      },
      beginTime: "",
      endTime: "",
      entrydate: "",
      deptList: [],
      genderList: [{id: 1, name: "男"}, {id: 2, name: "女"}],
      jobList: [],
      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      token: getToken()

    }
  },
  methods: {
    getDepartmentName(deptId) {
      const matchedDept = this.deptList.find(dept => dept.id === deptId);
      return matchedDept ? matchedDept.name : '';
    },
    getJobListName(job) {
      const matchedDept = this.jobList.find(jobs => jobs.id === job);
      return matchedDept ? matchedDept.name : '';
    },
    update(id) {
      //1. 打开窗口
      this.dialogVisible = true;
      //2. 发送请求
      selectById(id).then((result) => {
        if (result.data.code == 1) {
          this.disciple = result.data.data;
        }
      });

    },
    // 查询分页数据
    page() {
      emppage(
          this.disciple.name,
          this.disciple.job,
          this.disciple.deptId,
          this.beginTime,
          this.endTime,
          this.currentPage,
          this.pageSize
      ).then((res) => {
        console.log(res);
        if (res.data.code != 0) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
        }
      });
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 查询方法
    onSubmit() {
      this.currentPage = 1;
      this.page();
    },

    clearInfo() {
      this.emp = {
        createTime: "",
        deptId: "",
        entrydate: "",
        gender: "",
        id: null,
        image: "",
        job: "",
        name: "",
        password: "",
        updateTime: "",
        username: "",
      };

    },
    clear() {
      this.disciple = {
        createTime: "",
        deptId: "",
        entrydate: "",
        gender: "",
        id: null,
        image: "",
        job: "",
        name: "",
        password: "",
        updateTime: "",
        username: "",
      };
      this.beginTime = "";
      this.endTime = "";
      this.entrydate = "";
      this.page();
    },

    // 添加数据
    adds() {
      let operator;
      if (this.disciple.id) {
        //修改
        operator = update(this.disciple);
      } else {
        operator = add(this.disciple);
      }

      operator.then((resp) => {
        if (resp.data.code == "1") {
          this.dialogVisible = false;

          this.$message({message: "恭喜你，保存成功", type: "success"});

          //this.emp = {image: ""};
        } else {
          this.$message.error(resp.data.msg);
        }
        this.page();
      });
    },
    updateinfo(id) {
      //1. 打开窗口
      this.dialogVisible = true;
      //2. 发送请求
      selectById(id).then((result) => {
        if (result.data.code == 1) {
          this.disciple = result.data.data;
        }
      });
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.page();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.page();
    },
    //删除员工信息
    deletebyId(id) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //2. 发送AJAX请求
        deleteById(id).then((resp) => {
          if (resp.data.code == 1) {
            //删除成功
            this.$message.success("恭喜你，删除成功");
            //this.page();

          } else {
            this.$message.error(resp.data.msg);
          }
        });
      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除");
      });
      //this.page();
    },
    // 批量删除员工信息
    deleteByIds() {
      // 弹出确认提示框
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //用户点击确认按钮
        //1. 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id;
          alert('SV')
        }
        console.log(this.selectedIds);
        //2. 发送AJAX请求
        deleteById(this.selectedIds).then((resp) => {
          if (resp.data.code == "1") {
            //删除成功
            this.$message.success("恭喜你，删除成功");
            //this.page();
          } else {
            this.$message.error(resp.data.msg);
          }
        });
      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除");
      });

    },
    getjobList() {
      getJoblist().then(res => {
        console.log(res);
        if (res.data.code == 1) {
          this.jobList = res.data.data;
        }
      })
    },
    getdeptList() {
      findAll().then(res => {
        console.log(res);
        if (res.data.code == 1) {
          this.deptList = res.data.data;
        }
      })
    },
    //文件上传相关
    handleAvatarSuccess(res, file) {
      this.disciple.image = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 100;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },


  },
  mounted() {
    this.token = getToken();
    if (this.token != null) {
      this.page();
      this.getjobList();
      this.getdeptList();
    } else {
      this.$router.push('/login');
    }

  },
  watch: {
    entrydate(val) {
      if (val && val.length >= 2) {
        this.beginTime = val[0];
        this.endTime = val[1];
      } else {
        this.beginTime = "";
        this.endTime = "";
      }
    },
  }


};
</script>


<style>

</style>
